package com.hyg.lib_common.loginpart;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.R;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;
@Route(path = Constants.PATH_ACTIVITY_MODULE_USER_FORGETPASS)
public class ForgetPwdActivity extends BaseActivity {
    protected void onStop(){
        super.onStop();
        if(this.isFinishing()){
            myHandler.removeCallbacksAndMessages(null);
            Runtime.getRuntime().gc();
        }
    }
    private Button update_pwd;
    private ImageView back;
    private EditText et_code,et_phone,et_pass,et_name;
    private ToggleButton togglePwd;
    private Button getcode,forget;
    private String code="";
    private String phone="";
    private String password="";
    public String mphone = "[1][345789]\\d{9}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mcode = "\\d{4,6}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mpassword = "[A-Za-z0-9]{6,18}";//第一位是字母，后面加上4-15个
    private Timer mTimer = null;

    private MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private ForgetPwdActivity activity;
        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (ForgetPwdActivity) reference.get();
        }
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://修改密码
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeadLogin", jsondata+"");
                        if (status.equals("200")){
                            activity.editorn = activity.sn.edit();
                            activity.editorn.putString("phone", activity.phone);
                            activity.editorn.putString("password", activity.password);
                            activity.editorn.commit();
                            if (activity.pDialog.isShowing())
                                activity.pDialog.dismiss();
                            activity.pDialog = new SweetAlertDialog(activity, SweetAlertDialog.SUCCESS_TYPE);
                            activity.pDialog.setTitleText("密码修改成功");
                            activity.pDialog.setCancelable(false);
                            activity.pDialog.setConfirmButton("点我去登录", new SweetAlertDialog.OnSweetClickListener() {
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.cancel();
                                    Intent it = new Intent(activity, LoginActivity.class);// 跳转
                                    activity.startActivity(it);
                                    activity.finish();
                                    activity.overridePendingTransition(R.anim.fade, R.anim.hold);
                                }
                            });
                            activity.pDialog.show();
                        } else {
                            if (activity.pDialog.isShowing())activity.pDialog.dismiss();
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
                case 2://获取注册验证码
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String success = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeadLogin", jsondata+"");
                        if (success.equals("200")){
                            if(!message.equals("")) {
                                Toast.makeText(activity,message, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            if (activity.pDialog.isShowing())activity.pDialog.dismiss();
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
                case 100:   //提示关闭的对话框
                    activity.getcode.setText(activity.countdown + "s后可获取");
                    activity.getcode.setAlpha(0.5f);
                    if (0 == activity.countdown) {
                        //停止倒计时显示页面
                        activity.resume();
                        activity.stopTimer();
                        return;
                    }
                    activity.countdown--;
                    break;
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd);
        StatusBarUtil.setStatusBar(1,this,getResources().getColor(R.color.white),00,null,null,true);
        init();
    }

    public void init(){
        back = (ImageView)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {if(Utils.isFastClick()){return ;}
                Intent it = new Intent(ForgetPwdActivity.this, LoginActivity.class);// 跳转
                startActivity(it);
                ForgetPwdActivity.this.finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });

        update_pwd = (Button)findViewById(R.id.update_pwd);
        getcode = (Button)findViewById(R.id.getcode);
        et_code = (EditText)findViewById(R.id.et_code);
        et_phone = (EditText)findViewById(R.id.et_phone);
        et_pass = (EditText)findViewById(R.id.et_password);
        togglePwd = (ToggleButton) findViewById(R.id.togglePwd);
        togglePwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) { //如果选中，显示密码
                    et_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else { //否则隐藏密码
                    et_pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });

        update_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                phone = et_phone.getText().toString();
                password = et_pass.getText().toString();
                code = et_code.getText().toString();

                if (phone.equals("")) {
                    dialog("请填写手机号。");
                } else if (password.equals("")) {
                    dialog("密码不可为空，请填写密码。");
                }else if(code.equals("")){
                    dialog("请填写验证码。");
                }else {
                    if (!phone.matches(mphone)) {
                        dialog("手机号格式错误，请重新输入。");
                    } else if (!password.matches(mpassword)) {
                        dialog("密码格式不对或者包含非格式字符，请重新输入。");
                        et_pass.setText("");
                    }else if (!code.matches(mcode)) {
                        dialog("验证码格式错误，请重新输入。");
                    }  else {
                        ReviseLoading();
                        String str_tag = "1";
                        FormBody formBody = new FormBody.Builder()
                                .add("phone", phone)//设置参数名称和参数值
                                .add("newPassword", password)//设置参数名称和参数值
                                .add("smsCode", code)//设置参数名称和参数值
                                .build();
                        sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.resetAddr);
                    }
                }
            }
        });

        getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = et_phone.getText().toString();
                if (Utils.isFastClick()) {
                    return;
                }
                if (phone.equals("")) {
                    dialog("电话号码不可为空，请填写电话号码。");
                } else if (!phone.matches(mphone)) {
                    dialog("电话号码格式不对，请重新输入。");
                    et_phone.setText("");
                } else {
                    {
                        et_code.setHint("请注意查看短信");
                        startTimer();
                        String str_tag = "2";
                        FormBody formBody = new FormBody.Builder()
                                .add("phone", phone)//设置参数名称和参数值
                                .build();
                        sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.codeaddr);
                    }
                }
            }
        });
    }

    public void ReviseLoading(){
        if (pDialog.isShowing())
            pDialog.dismiss();
        View view = View.inflate(ForgetPwdActivity.this, R.layout.dialog_loading, null);
        TextView loadingText = (TextView) view.findViewById(R.id.loadingText);
        loadingText.setText("正在修改中...");
        pDialog = new SweetAlertDialog(ForgetPwdActivity.this, SweetAlertDialog.NORMAL_TYPE);
        pDialog.setCustomView(view);
        pDialog.setConfirmButton("好的", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        pDialog.show();
    }

    public void dialog(String text){
        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(ForgetPwdActivity.this, SweetAlertDialog.ERROR_TYPE);
        pDialog.setTitleText("格式错误");
        pDialog.setContentText(text);
        pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.cancel();
            }
        });
        pDialog.show();
    }

    //开始倒计时
    private void startTimer() {
        //点击获取验证码后改变按钮的状态,让按钮不可点击
        getcode.setClickable(false);
        if (mTimer == null) {
            mTimer = new Timer(true);
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {

                myHandler.sendEmptyMessage(100);
            }
        }, 0, 1000);
    }

    private int countdown = 60;

    private void resume() {
        stopTimer();
        countdown = 45;
        //倒计时结束后,让按钮重新可点击
        getcode.setClickable(true);
        getcode.setText("获取验证码");
        getcode.setAlpha(0.9f);
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    //改写返回键功能
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ForgetPwdActivity.this.finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}